<template>
  <div class="app-container">
    <!-- 添加搜索框 -->
    <div class="filter-container">
      <el-input v-model="listQuery.machineId" placeholder="机器ID" clearable style="width: 180px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.machineNo" placeholder="机器编号" clearable style="width: 180px;" class="filter-item"
      @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.machineName" placeholder="机器名称" clearable style="width: 180px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.machineStatus" placeholder="状态" clearable class="filter-item" style="width: 120px"
        @keyup.enter.native="handleFilter">
        <el-option v-for="item in machineStatusOptions" :key="item.key" :label="item.display_name"
          :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button v-waves class="filter-item" type="success" icon="el-icon-circle-plus-outline"
        @click="handleAddMachine">增加</el-button>
    </div>

    <!-- 显示表格数据 -->
    <el-table v-loading="listLoading" :key="tableKey" :data="list" fit highlight-current-row style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column label="机器ID" prop="machineId" sortable="custom" align="center" min-width="105px">
        <template slot-scope="scope">
          <span>{{ scope.row.machineId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="机器编号" prop="machineNo" sortable="custom" align="center" min-width="105px">
        <template slot-scope="scope">
          <span>{{ scope.row.machineNo }}</span>
        </template>
      </el-table-column>

      <el-table-column label="名称" align="center" min-width="215px">
        <template slot-scope="scope">
          <span>{{ scope.row.machineName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="图片" align="center" min-width="75px">
        <template slot-scope="scope">
          <span>{{ scope.row.machineImg }}</span>
        </template>
      </el-table-column>

      <el-table-column label="价格" sortable="custom" prop="machinePrice" align="center" min-width="105px">
        <template slot-scope="scope">
          <span>￥ {{ scope.row.machinePrice }}</span>
        </template>
      </el-table-column>


      <el-table-column label="更新时间" prop="updatedTime" sortable="custom" min-width="135px" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" class-name="status-col" min-width="90px">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="机器详情：" width="200" trigger="click"
            :content="scope.row.machineDescription">
            <el-button :type="scope.row.machineStatus | statusFilter" plain slot="reference" size="small ">{{
              scope.row.machineStatus | typeFilter }}</el-button>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column v-if="true" label="操作" align="center" min-width="80px">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 页码显示插件 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <!-- 更新机器信息表单 -->
    <el-dialog v-if="true" :visible.sync="dialogFormVisible" title="更改机器信息">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <!-- 一条数据 prop 为 temp 中的一条数据，用于回显-->
        <el-form-item label="机器ID" prop="machineId">
          <el-input v-model="temp.machineId" style="width: 220px" :disabled="true" />
        </el-form-item>
        <el-form-item label="机器编号" prop="machineNo">
          <el-input v-model.number="temp.machineNo" style="width: 220px" :disabled="true" />
        </el-form-item>
        <el-form-item label="名称" prop="machineName">
          <el-input v-model="temp.machineName" />
        </el-form-item>
        <el-form-item label="样式图" prop="machineImg">
          <el-input v-model="temp.machineImg" />
        </el-form-item>
        <el-form-item label="价格" prop="machinePrice">
          <el-input v-model.number="temp.machinePrice" :disabled="true"  />
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="temp.machineStatus" class="filter-item" placeholder="请选择">
            <el-option v-for="item in machineStatusOptions" :key="item.key" :label="item.display_name"
              :value="item.key" />
          </el-select>
        </el-form-item>

        <el-form-item label="描述" prop="machineDescription">
          <el-input v-model="temp.machineDescription" type="textarea" placeholder="请输入描述信息" rows="5" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData">确认</el-button>
      </div>

    </el-dialog>



    <!-- 增加机器的表单 -->
    <el-dialog v-if="true" :visible.sync="addDialogFormVisible" title="增加机器">
      <el-form ref="addDataForm" :rules="rules" :model="temp" label-position="right" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="机器编号" prop="machineNo">
          <el-input v-model.number="temp.machineNo" placeholder="请输入机器编号"/>
        </el-form-item>
        <el-form-item label="名称" prop="machineName">
          <el-input v-model="temp.machineName" placeholder="请输入机器名称"/>
        </el-form-item>
        <el-form-item label="图片" prop="machineImg">
          <el-input v-model="temp.machineImg" placeholder="请上传机器图片"/>
        </el-form-item>
        <el-form-item label="价格" prop="machinePrice" placeholder="请输入机器价格">
          <el-input v-model.number="temp.machinePrice" />
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="temp.machineStatus" class="filter-item" placeholder="请选择机器状态">
            <el-option v-for="item in machineStatusOptions" :key="item.key" :label="item.display_name"
              :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="machineDescription">
          <el-input v-model="temp.machineDescription" type="textarea" placeholder="请输入描述信息" rows="5" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addMachine">确认</el-button>
      </div>

    </el-dialog>
  </div>
</template>


<script>
  import waves from '@/directive/waves'            // Waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  // import { fetchSeries } from '@/api/init'
  import { fetchList, updateMachineApi, addMachineApi } from '@/api/machine'
  const machineStatusOptions = [
    { key: 0, display_name: '禁止' },
    { key: 1, display_name: '可用' }
  ]

  // 
  const calendarTypeKeyValue = machineStatusOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    // 分页组件
    components: { Pagination },
    // 按钮波浪样式
    directives: {
      waves
    },
    // 
    filters: {
      // 按钮样式图标
      statusFilter(status) {
        const statusMap = {
          0: 'danger',
          1: 'success'
        }
        return statusMap[status]
      },
      // 状态过滤器
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        // 
        tableKey: 0,
        // 封装所有条查询的数据
        list: null,
        // 总查询条数
        total: 0,
        // 
        listLoading: true,
        // 封装的查询条件对象
        listQuery: {
          page: 1,
          limit: 5,
          machineId: undefined,
          machineNo: undefined,
          machineName: undefined,
          machineStatus: undefined,
          orderBy: undefined
        },
        machineStatusOptions,
        // 临时存储表单的修改数据
        // 
        temp: {
          machineId: undefined,
          machineNo: undefined,
          machineImg: undefined,
          machineName: undefined,
          machinePrice: undefined,
          machineDescription: undefined,
          machineStatus: undefined,
          createdTime: undefined,
          updatedTime: undefined,
        },
        mytemp: {
          categoryName: ""
        },
        // dialogFormVisible：编辑或添加Form的可见性
        dialogFormVisible: false,
        addDialogFormVisible: false,
        addCategoryFormVisible: false,
        // 工件类别列表,字典格式
        options: [],
        // 工件类别名字数组
        categoryNameOptions: [],
        rules: {
          machineName: [
            { required: true, message: '请输入机器名称', trigger: 'blur' }
          ],
          machineNo: [
            { required: true, message: '请输入机器编号', trigger: 'blur' }
          ],
          machineImg: [
            { required: true, message: '请上传机器图片', trigger: 'blur' }
          ],
          machinePrice: [
            { required: true, message: '请输入机器价格', trigger: 'blur' },
            { type: 'number', message: '进价必须为数字值' }
          ],
          machineDescription: [
            { required: false, message: '请输入机器描述' }
          ],
        },
        downloadLoading: false
      }
    },
    // 创建完 data 等初始化数据后,挂载数据之前
    created() {
      // 获取总记录条数和查询到的记录
      this.getList()
    },
    methods: {
      // checkPermission,
      // 查询所有条数据
      getList() {
        // 表示加载 list 数据的状态为 true
        this.listLoading = true
        // 发送 ajax 请求,并携带相应的条件对象,初始化时条件对象为空
        fetchList(this.listQuery).then(response => {
          // response.data 是返回的 Vo 通过浏览器封装的一层对象 {code, msg, data}
          if (response.data.code == 10000) {
            // 后端的 data 中封装了 items 和 total 两个元素
            this.list = response.data.data.items
            this.total = response.data.data.total
          } else {
            // 弹窗显示错误类型
            this.$message({
              // message: response.data.message,
              message: "查询到0条记录！",
              type: 'error'
            })
          }
          this.listLoading = false

          // Just to simulate the time of the request
          // setTimeout(() => {
          //   this.listLoading = false
          // }, 0.5 * 1000)

        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      // 增加机器信息
      handleAddMachine() {
        this.temp = Object.assign({}, {})
        this.addDialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['addDataForm'].clearValidate()
        })
      },
      addMachine() {
        // 获取表单对象，验证 rules 得到验证的值 valid 为 true 或者 false
        this.$refs['addDataForm'].validate((valid) => {
          // 验证通过
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            addMachineApi(tempData).then(response => {
              if (response.data.code === 10000) {
                this.listQuery.orderBy = "createdTime desc"
                this.getList()
                this.$notify({
                  title: '成功',
                  message: response.data.message,
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '错误',
                  message: response.data.message,
                  type: 'error',
                  duration: 2000
                })
              }
              this.addDialogFormVisible = false
            })
          }
        })
      },
      // 点击小箭头排序
      sortChange(data) {

        const { prop, order } = data
        if (order === 'ascending') {
          this.listQuery.orderBy = prop + ' asc'

        } else if (order === 'descending') {
          this.listQuery.orderBy = prop + ' desc'
        } else {
          this.listQuery.orderBy = null
        }
        this.handleFilter()
      },
      // 执行编辑操作，表格中的一行数据
      handleUpdate(row) {
        // 数据拷贝，备份，Object.assign，浅拷贝
        this.temp = Object.assign({}, row) // copy obj
        // 绑定 data 中实体machine的 machineCategoryId
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      parseTime,
      // 更新表单
      updateData() {
        // 获取表单对象，验证 rules 得到验证的值 valid 为 true 或者 false
        this.$refs['dataForm'].validate((valid) => {
          // 验证通过
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updateMachineApi(tempData).then(response => {
              if (response.data.code === 10000) {
                this.getList()
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '错误',
                  message: response.data.message,
                  type: 'error',
                  duration: 2000
                })
              }
              this.dialogFormVisible = false
            })
          }
        })
      },
      // 下载表格到本地 excel 中
      // handleDownload() {
      //   this.downloadLoading = true
      //   import('@/vendor/Export2Excel').then(excel => {
      //     const tHeader = ['库存编号', '品牌', '车系', '型号', '颜色', '进价', '售价', '入库时间', '状态']
      //     const filterVal = ['id', 'brandName', 'seriesName', 'type', 'color', 'price', 'salePrice', 'createTime', 'status']
      //     const data = this.formatJson(filterVal, this.list)
      //     excel.export_json_to_excel({
      //       header: tHeader,
      //       data,
      //       filename: '库存信息'
      //     })
      //     this.downloadLoading = false
      //   })
      // },
      // formatJson(filterVal, jsonData) {
      //   return jsonData.map(v => filterVal.map(j => {
      //     if (j === 'createTime') {
      //       return parseTime(v[j])
      //     } else if (j === 'status') {
      //       return calendarTypeKeyValue[v[j]]
      //     } else {
      //       return v[j]
      //     }
      //   }))
      // }
    }
  }
</script>